<template>
  <view>
    <Search />
    <!-- @sedTabsIndex这是子组件自己定义的函数名 
    getTabsIndex是父组件这边需要用的函数-->
    <Tabs :tabsData="tabsData" @sedTabsIndex="getTabsIndex" />
    cid= {{ cid }}
    <!-- 渲染列表页里的每一个列表 -->
    <view class="goods_list">
      <GoodsItem v-for="item in goods" :key="item.goods_id" :item="item" />
    </view>
    <view class="tips" v-if="!hasMore">😁别再扒扒了，我也是有底线的！！</view>
  </view>
</template>

<script>
import Search from "@/components/Search/index";
import Tabs from "@/components/Tabs/index";
import GoodsItem from "@/components/GoodsItem/index";
import { getGoodsList } from "@/api";
export default {
  components: {
    Search,
    Tabs,
    GoodsItem,
  },
  data() {
    return {
      tabsData: [
        { id: 1, text: "综合" },
        { id: 2, text: "销量" },
        { id: 3, text: "价格" },
      ],
      cid: "",
      pagenum: 1, //页码
      pagesize: 10, //页容量
      goods: [],
      hasMore: true,
    };
  },
  onLoad({ cid }) {
    this.cid = cid || 927;
    this.getGoodsData();
  },
  // 即将触底时，触发触底事件
  onReachBottom() {
    console.log("触发触底事件");
    if (this.hasMore) {
      // 页码加一
      this.pagenum++;
      // 还应该重新发送网咯请求
      this.getGoodsData();
    }
  },
  async onPullDownRefresh() {
    console.log("用户下拉刷新页面了");
    // 清空已添加的数据，并使数据回到初始化的情况：
    this.pagenum = 1;
    this.goods = [];
    this.hasMore = true;
    // 根据重新获取的数据，重新发起请求
    await this.getGoodsData();
    //  等待请求完成，之后，就结束下拉刷新：
    uni.stopPullDownRefresh();
  },
  methods: {
    async getGoodsData() {
      // 发送请求完成前：设置加载提示：
      uni.showLoading({
        title: "疯狂加载中……",
      });
      const res = await getGoodsList({
        // data: {  不要写在data里面！！！不好观察
        //   cid: this.cid,
        //   pagenum: this.pagenum,
        //   pagesize: this.pagesize,
        // },
        cid: this.cid,
        pagenum: this.pagenum,
        pagesize: this.pagesize,
      });
      // 解构出列表的总条数；然后一次判断是否还要发送请求(hasMore)
      const { goods, total } = res.data.message;
      // 加载页码的时候，应该把原来的数据保留，新追加新的数据
      this.goods = [...goods, ...this.goods];
      uni.hideLoading();
      if (total === this.goods.length) {
        this.hasMore = false;
      }
    },
    getTabsIndex(index) {
      console.log("获得子组件传递过来的索引值7777777", index);
    },
  },
};
</script>

<style lang="less" scoped>
.tips {
  height: 100rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>